package com.demo.net.ui;

import javax.swing.*;
import java.awt.*;
import java.io.*;
import java.net.Socket;

public class Client extends JFrame {
    private static final int WIDTH = 600;
    private static final int HEIGHT = 400;
    private OutputStream out;

    private PrintStream ps ;

    public Client() throws IOException {
        this.initUI();
        setVisible(true);
        this.initSocket();
    }

    private void initSocket() throws IOException {
        Socket socket = new Socket("localhost", 10086);
        this.out = socket.getOutputStream();
        this.ps = new PrintStream(out);
        BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        while (true) {
            String line = br.readLine();
            if(null == line) break;
            System.out.println("服务器响应:" + line);
        }
//        new Thread(()->{
//            // 不同的读数据
//            while (true) {
//                try {
//                    String line = br.readLine();
//                    System.out.println("服务器响应:" + line);
//                } catch (IOException e) {
//                    e.printStackTrace();
//                }
//            }
//        });
    }

    // 初始化窗口
    private void initUI() {
        Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
        setTitle("Socket客户端");
        setSize(WIDTH, HEIGHT);
        setLocation((screenSize.width - WIDTH) / 2, (screenSize.height - HEIGHT) / 2);
        this.setDefaultCloseOperation(EXIT_ON_CLOSE);

        JPanel panel = new JPanel();
//        panel.setLayout(new BorderLayout());
        setContentPane(panel);
        //创建文本框
        JTextArea textArea = new JTextArea();
        textArea.setForeground(Color.BLACK);
        textArea.setBackground(Color.YELLOW);
        textArea.setLineWrap(true);
        textArea.setBounds(10, 10, WIDTH - 20, 100);
        textArea.setRows(5);
        panel.add(textArea);
        // 创建btn
        JButton btn = new JButton("发送");
//        btn.setBounds(10, 10, 80, 30);
        panel.add(btn);

        btn.addActionListener(e -> {
            if(out != null && textArea.getText().length() > 0) {
//                try {
////                    out.write(textArea.getText().getBytes());
////                    out.flush();
//
//                } catch (IOException ex) {
//                    ex.printStackTrace();
//                }
                ps.println(textArea.getText());
                textArea.setText("");
            }
        });
    }

    public static void main(String[] args) throws IOException {
        new Client();
    }
}
